<template>
  <div class="app-container">
    <!-- 公共顶部 -->
    <large-screen-header />
    <!-- 主体部分 -->
    <div class="app-main">
      <!-- 左侧 -->
      <div class="app-left">
        <div class="app-left-item">
          <!-- 次级标题 -->
          <subheadings :name="'全国已有地震地质灾害数量'" />
          <!-- 统计 -->
          <disaster-number @getType="getType" />
        </div>
        <div class="app-left-item">
          <subheadings :name="'各省（直辖市）地震地质灾害发育数量图'" />
          <BarChart />
        </div>
        <div class="app-left-item">
          <subheadings :name="'地震地质灾害系统服务统计'" />
          <service-statistics />
        </div>
      </div>
      <!-- 中心部分 -->
      <div class="app-center">
        <!-- 标题 -->
        <headline :name="'地震地质灾害评估成果'" />
        <!-- 地图 -->
        <div class="app-map">
          <SystemSelect :styles="{ position: 'absolute', top: '-30px', left: '42px' }" />
          <!-- <IndexMap></IndexMap> -->
          <OlMap
            ref="olmapRef"
            refId="geologicaldisaster"
            style="height: 100%"
            @getMap="getMap"
            @mapClick="mapClick"
          ></OlMap>
          <CustomMenu
            style="position: absolute; left: 42px; bottom: 140px"
            :options="menuOptions"
            @onOptionClick="handleOptionClick"
          />
          <ComLegend
            v-if="!hideComLegend"
            style="position: absolute; left: 42px; bottom: 220px"
            title="图例"
            subTitle=""
            :items="legendItems"
            :items-per-column="10"
          ></ComLegend>
          <p>
            <span style="position: absolute; top: 20px; right: 40px; font-size: 14px; color: #ffffff">{{
              radioShowLabel
            }}</span>
          </p>
        </div>
      </div>
      <!-- 右侧 -->
      <div class="app-right">
        <div class="app-right-item">
          <!-- 次级标题 -->
          <subheadings :name="'评估类型'" />
          <EvaluationType @getTypeValue="getTypeValue" />
        </div>
        <div class="app-right-item">
          <subheadings :name="'全国地震地质灾害概况'" />
          <DisasterOverview :typeData="paramsData" />
        </div>
        <div class="app-right-item">
          <subheadings :name="'危险性面积统计分析'" />
          <HazardousArea :typeData="paramsData" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="Index">
// 引入 Element Plus 默认样式文件
import 'element-plus/theme-chalk/index.css';
//地图
// import IndexMap from '@/views/securityActivity/map/index.vue';
import DisasterNumber from './components/DisasterNumber.vue';
import DisasterOverview from './components/DisasterOverview.vue';
import ServiceStatistics from './components/ServiceStatistics.vue';
import EvaluationType from './components/EvaluationType.vue';
import BarChart from './components/BarChart.vue';
import HazardousArea from './components/HazardousArea.vue';

// 系统选择
import SystemSelect from '@/components/SystemSelect';
import { getActivityMap } from '@/api/securityActivity.js';
// start
import OlMap from '@/components/Olmap';
import { Style, Circle as CircleStyle, Fill, Stroke, Icon, Text } from 'ol/style';
import Feature from 'ol/Feature';
import { Point } from 'ol/geom';
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer';
import { OSM, Vector as VectorSource } from 'ol/source';
import yellowMarkerImg from '@/assets/map/image/newImage/yelloMarker.png';
import CustomMenu from '@/components/CustomMenu';
import { GeoJSON as GeoJSonFormat } from 'ol/format';
import { ref } from 'vue';
import ComLegend from '@/components/ComLegend';
import { getChinaBaseMap, getGridLayer } from '@/map/projMap.js';
import { useRouter } from 'vue-router';
import { getMapDisaster,getResultLogisticGrowth } from '@/api/geologicalDisaster.js';
import { getSqlTempLayer } from '@/utils/sqlTempLayersSet';
// end
const router = useRouter();
const paramsData = ref();
// start
const mapInstance = ref(null);
const vectorLayer = ref(null);
const hideComLegend = ref(false);

const olmapRef = ref(null);
const menuOptions = ['地图', '影像图', '地形图'];
const radioShowLabel = ref('');
const radioLabels = [
  { title: '设定地震', value: ['VI度', 'VII度', 'VIII度', 'IX度', 'X度', 'XI度'] },
  { title: '场地类别', value: ['活动构造区', '稳定大陆区'] },
  { title: '抗震设防烈度', value: ['7度', '8度', '9度'] },
  { magnitudeTitle: '震级范围', dateTitle: '时间范围' },
];
const quakeTypes = ['地震滑坡', '砂土液化', '软土震陷', '地表破裂带'];
const legendItems = ref([
  { label: '极低危险', color: 'rgba(118,183,74,1)', w: 10, h: 8, r: 0 },
  { label: '低危险', color: 'rgba(173,217,83,1)', w: 10, h: 8, r: 0 },
  { label: '中危险', color: 'rgba(255,253,97,1)', w: 10, h: 8, r: 0 },
  { label: '高危险', color: 'rgba(241,158,75,1)', w: 10, h: 8, r: 0 },
  { label: '极高危险', color: 'rgba(234,72,63,1)', w: 10, h: 8, r: 0 },
]);
// end

// start
const getMap = (map) => {
  mapInstance.value = map.value;

  addProvinceNameLayer();
};
const mapClick = async (event) => {
  const clickedFeature = mapInstance.value.forEachFeatureAtPixel(event.pixel, (feature) => feature);
  console.log('click', clickedFeature);
  if (clickedFeature && clickedFeature.get('adcode')) {
    router.push({
      path: '/geologicalDisaster/second',
      query: { code: clickedFeature.get('adcode'), provinceName: clickedFeature.get('name') },
    });
  }
};
const handleMenuButtonClick = (button) => {
  console.log('Button clicked:', button.label);
  // 在这里进行按钮点击后的逻辑处理
};
function addProvinceNameLayer() {
  const geojsonSource = new VectorSource({
    url: getChinaBaseMap,
    format: new GeoJSonFormat(),
  });

  // 创建省份名称文本图层
  const textLayer = new VectorLayer({
    source: geojsonSource,
    zIndex: 1,
    id: 'province',
    style: function (feature) {
      const textstyle = new Style({
        fill: new Fill({ color: 'transparent' }),
        text: new Text({
          font: '10px Calibri,sans-serif',
          fill: new Fill({ color: '#fff' }),
          text: feature.get('name'),
        }),
      });
      return textstyle;
    },
  });

  mapInstance.value.addLayer(textLayer);
}

function setQuakeLayerVisible(layerId, flag) {
  let layers = mapInstance.value.getLayers();
  layers.forEach((layer) => {
    let lid = layer.get('id');
    if (lid) {
      if (lid.indexOf(layerId) != -1) {
        layer.setVisible(flag);
      }
    }
  });
}

function removeQuakeLayer(layerId) {
  let layers = mapInstance.value.getLayers();
  for (let i = 0; i < layers.length; i++) {
    let layer = layers[i];
    let lid = layer.get('id');
    if (lid) {
      if (lid.indexOf(layerId) != -1) {
        mapInstance.value.removeLayer(layer);
      }
    }
  }
}

function getQuakeLayerById(layerId) {
  let returnLayer;
  let layers = mapInstance.value.getLayers();
  layers.forEach((layer) => {
    if (layer.get('id') == layerId) {
      returnLayer = layer;
    }
  });

  return returnLayer;
}
//地震滑坡图层
function showDZHPLayer(urlType) {
  setQuakeLayerVisible('dzhp_level', false);
  setQuakeLayerVisible('rtzx_level', false);
  setQuakeLayerVisible('dbpld_level', false);
  setQuakeLayerVisible('styh_level', false);

  let layerId = 'dzhp_level_' + urlType;
  let returnLayer = getQuakeLayerById(layerId);

  if (returnLayer) {
    setQuakeLayerVisible(layerId, true);
  } else {
    /*let pack = process.env.NODE_ENV === 'development';
    let url = pack
      ? '/iserver/services/map-demtif/rest/maps/逻辑斯蒂模型_计算_1692611889384_' + urlType
      : '/iserver/services/map-demtif/rest/maps/逻辑斯蒂模型_计算_1693795938950_' + urlType;
    getGridLayer(url).then((layer) => {
      layer.set('id', layerId);
      mapInstance.value.addLayer(layer);
    });*/
    try {
      //根据烈度类型获取大屏展示任务地震滑坡逻辑斯蒂计算结果并添加图层
      getResultLogisticGrowthByTYPE(urlType);
    } catch (error) {
      console.log(error);
    }
  }
}

//根据烈度类型获取大屏展示任务地震滑坡逻辑斯蒂计算结果并添加图层
const getResultLogisticGrowthByTYPE = async (dzIntensity) => {
  let res = await getResultLogisticGrowth(dzIntensity);
  console.log(res);
  let data = res.data?res.data:[];
  if (data && data.length > 0) {
    data.forEach((item) => {
      let taskId = item.taskId;
      let filePath = item.filePath;
      let url = '/iserver/services/map-demtif/rest/maps/' + filePath;
      let layerId = 'dzhp_level_' + dzIntensity + "_" + taskId;
      console.log(layerId+","+url);
      getGridLayer(url).then((layer) => {
        layer.set('id', layerId);
        mapInstance.value.addLayer(layer);
      });
    });
  }
};

//软土震陷图层
function showRTZXLayer(type) {
  setQuakeLayerVisible('dzhp_level', false);
  setQuakeLayerVisible('rtzx_level', false);
  setQuakeLayerVisible('dbpld_level', false);
  setQuakeLayerVisible('styh_level', false);

  let layerId = 'rtzx_level_' + type;
  let returnLayer = getQuakeLayerById(type);

  if (returnLayer) {
    setQuakeLayerVisible(layerId, true);
  } else {
    let url = '/iserver/services/map-fxfzdzzh/rest/maps/dzzh_soft_soil_polygon_evaluate_result@fxfzdzzh';
    let sqlText = "type = '" + type + "' AND flag = '1'";
    getSqlTempLayer(url, sqlText).then((layer) => {
      layer.set('id', layerId);
      mapInstance.value.addLayer(layer);
    });
  }
}

//地表破裂带图层
function showDBPLDLayer(magnitudeRange1, magnitudeRange2, dateRange1, dateRange2) {
  setQuakeLayerVisible('dzhp_level', false);
  setQuakeLayerVisible('rtzx_level', false);
  setQuakeLayerVisible('styh_level', false);
  setQuakeLayerVisible('dbpld_level', false);
  //因为是范围，不是固定图层，所以直接删除旧的地表破裂带图层，重新请求
  removeQuakeLayer('dbpld_level');

  let url_ = '/iserver/services/map-fxfzdzzh/rest/maps/dzzh_surface_rupture@fxfzdzzh';
  let url_fault = '/iserver/services/map-fxfzdzzh/rest/maps/dzzh_surface_rupture_fault@fxfzdzzh';
  let url_stimate = '/iserver/services/map-fxfzdzzh/rest/maps/dzzh_seismogenic_structure_stimate@fxfzdzzh';
  let sqlText_ = '',
    sqlText_fault = '',
    sqlText_stimate = '';

  //如果筛选条件都为空，默认显示最新
  if (magnitudeRange1 == '' && magnitudeRange2 == '' && dateRange1 == '' && dateRange2 == '') {
    sqlText_ = "source_from='1' and del_flag='0' order by earth_quake_time desc limit 1";
    sqlText_fault =
      " num in (select num from dzzh_surface_rupture where source_from='1' and del_flag='0' order by earth_quake_time desc limit 1)";
    sqlText_stimate =
      "num in (select num from dzzh_surface_rupture where source_from='1' and del_flag='0' order by earth_quake_time desc limit 1)";
  } else {
    sqlText_ =
      'earth_quake_level>=' +
      magnitudeRange1 +
      ' and earth_quake_level<=' +
      magnitudeRange2 +
      " and earth_quake_time>='" +
      dateRange1 +
      "' and earth_quake_time<='" +
      dateRange2 +
      "' and del_flag='0'";
    sqlText_fault =
      'earth_quake_level>=' +
      magnitudeRange1 +
      ' and earth_quake_level<=' +
      magnitudeRange2 +
      " and earth_quake_time>='" +
      dateRange1 +
      "' and earth_quake_time<='" +
      dateRange2 +
      "' and del_flag='0'";
    sqlText_stimate =
      'earth_quake_level>=' +
      magnitudeRange1 +
      ' and earth_quake_level<=' +
      magnitudeRange2 +
      " and earth_quake_time>='" +
      dateRange1 +
      "' and earth_quake_time<='" +
      dateRange2 +
      "' and del_flag='0'";
  }

  //地表破裂带震源
  getSqlTempLayer(url_, sqlText_).then((layer) => {
    layer.set('id', 'dbpld_level');
    mapInstance.value.addLayer(layer);
  });

  //地表破裂带
  getSqlTempLayer(url_fault, sqlText_fault).then((layer) => {
    layer.set('id', 'dbpld_level');
    mapInstance.value.addLayer(layer);
  });

  //发震构造评估区域
  getSqlTempLayer(url_stimate, sqlText_stimate).then((layer) => {
    layer.set('id', 'dbpld_level');
    mapInstance.value.addLayer(layer);
  });
}

//砂土液化图层，暂时有地震滑坡图层代替
function showSTYHLayer(type) {
  setQuakeLayerVisible('dzhp_level', false);
  setQuakeLayerVisible('rtzx_level', false);
  setQuakeLayerVisible('dbpld_level', false);
  setQuakeLayerVisible('styh_level', false);

  let layerId = 'styh_level_' + type;
  let returnLayer = getQuakeLayerById(layerId);

  if (returnLayer) {
    setQuakeLayerVisible(layerId, true);
  } else {
    let pack = process.env.NODE_ENV === 'development';
    let url = pack
      ? '/iserver/services/map-demtif/rest/maps/逻辑斯蒂模型_计算_1692611889384_' + type
      : '/iserver/services/map-demtif/rest/maps/逻辑斯蒂模型_计算_1693797282404_' + type;
    getGridLayer(url).then((layer) => {
      layer.set('id', layerId);
      mapInstance.value.addLayer(layer);
    });
  }
}

const createVectorLayer = () => {
  vectorLayer.value = new VectorLayer({
    source: new VectorSource(),
    zIndex: 2,
  });
  mapInstance.value.addLayer(vectorLayer.value);
};
const addRandomPoints = async (type) => {
  if (!vectorLayer.value) {
    return;
  }
  let res = await getMapDisaster({ type });
  let data = res.data?.list;
  if (data && data.length > 0) {
    data.forEach((item) => {
      const point = new Feature({
        geometry: new Point([item.lon, item.lat]),
      });
      const style = new Style({
        image: new Icon({
          src: yellowMarkerImg, // 图片路径
          scale: 1, // 图片缩放比例
        }),
        text: new Text({
          text: item.num.toString(), // 将数字转换为字符串显示
          offsetY: -5, // 调整数字在图标上方的位置
          fill: new Fill({ color: 'rgba(5, 4, 38, 1)' }),
          font: 'normal 13px Arial', // 设置字体样式
        }),
      });
      point.setStyle(style);
      vectorLayer.value.getSource().addFeature(point);
    });
  }
};
const handleOptionClick = (option, index) => {
  console.log(`Selected option in parent component: ${option}----${index}`);
  // 在这里处理选项点击事件，例如执行特定操作或更新数据

  if (index == 0) {
    olmapRef.value.showChinaBaseMapLayer();
  } else if (index == 1) {
    olmapRef.value.showTiandituImgMapLayer();
  } else if (index == 2) {
    olmapRef.value.showDemMapLayer();
  }
};
// end

const getType = (params) => {
  hideComLegend.value = true;
  radioShowLabel.value = quakeTypes[params - 1];

  if (vectorLayer.value) {
    mapInstance.value.removeLayer(vectorLayer.value);
  }

  setQuakeLayerVisible('dzhp_level', false);
  setQuakeLayerVisible('rtzx_level', false);
  setQuakeLayerVisible('dbpld_level', false);
  setQuakeLayerVisible('styh_level', false);
  createVectorLayer();
  addRandomPoints(params);
};

const getTypeValue = (params) => {
  paramsData.value = params;
  hideComLegend.value = false;
  if (vectorLayer.value) {
    mapInstance.value.removeLayer(vectorLayer.value);
  }

  if (params.parentType == 4) {
    let index1 = params.parentType - 1;
    let label1 = radioLabels[index1].magnitudeTitle;
    let label2 = radioLabels[index1].dateTitle;
    if (
      params.magnitudeRange1 != '' &&
      params.magnitudeRange2 != '' &&
      params.dateRange1 != '' &&
      params.dateRange2 != ''
    ) {
      radioShowLabel.value =
        label1 +
        '：' +
        params.magnitudeRange1 +
        ' — ' +
        params.magnitudeRange2 +
        '，' +
        label2 +
        '：' +
        params.dateRange1 +
        ' — ' +
        params.dateRange2;
    } else if (
      params.dateRange1 != '' &&
      params.dateRange2 != '' &&
      (params.magnitudeRange1 == '' || params.magnitudeRange2 == '')
    ) {
      radioShowLabel.value = label2 + '：' + params.dateRange1 + ' — ' + params.dateRange2;
    } else if (
      params.magnitudeRange1 != '' &&
      params.magnitudeRange2 != '' &&
      (params.dateRange1 == '' || params.dateRange2 == '')
    ) {
      radioShowLabel.value = label1 + '：' + params.magnitudeRange1 + ' — ' + params.magnitudeRange2;
    } else {
      radioShowLabel.value = '';
    }
  } else {
    let index1 = params.parentType - 1;
    let index2 = params.childType - 1;
    let label1 = radioLabels[index1].title;
    let label2 = radioLabels[index1].value[index2];
    radioShowLabel.value = label1 + '：' + label2;
  }

  if (params.parentType == 1) {
    //加载地震滑坡地图图层
    let type = params.childType + 5;
    showDZHPLayer(type);

    legendItems.value = [
      { label: '极低危险', color: 'rgba(118,183,74,1)', w: 10, h: 8, r: 0 },
      { label: '低危险', color: 'rgba(173,217,83,1)', w: 10, h: 8, r: 0 },
      { label: '中危险', color: 'rgba(255,253,97,1)', w: 10, h: 8, r: 0 },
      { label: '高危险', color: 'rgba(241,158,75,1)', w: 10, h: 8, r: 0 },
      { label: '极高危险', color: 'rgba(234,72,63,1)', w: 10, h: 8, r: 0 },
    ];
  } else if (params.parentType == 2) {
    //加载砂土液化地图图层
    let type = params.childType + 5;
    showSTYHLayer(type);

    legendItems.value = [
      { label: '极低危险', color: 'rgba(118,183,74,1)', w: 10, h: 8, r: 0 },
      { label: '低危险', color: 'rgba(173,217,83,1)', w: 10, h: 8, r: 0 },
      { label: '中危险', color: 'rgba(255,253,97,1)', w: 10, h: 8, r: 0 },
      { label: '高危险', color: 'rgba(241,158,75,1)', w: 10, h: 8, r: 0 },
      { label: '极高危险', color: 'rgba(234,72,63,1)', w: 10, h: 8, r: 0 },
    ];
  } else if (params.parentType == 3) {
    //加载软土震陷图层
    let type = params.childType + 6;
    showRTZXLayer(type);

    legendItems.value = [
      { label: '不震陷', color: 'rgba(118,183,74,1)', w: 10, h: 8, r: 0 },
      { label: '震陷', color: 'rgba(241,158,75,1)', w: 10, h: 8, r: 0 },
    ];
  } else if (params.parentType == 4) {
    //加载地震破裂带图层 {parentType: 4, magnitudeRange1: '', magnitudeRange2: '', dateRange1: '', dateRange2: ''}
    showDBPLDLayer(params.magnitudeRange1, params.magnitudeRange2, params.dateRange1, params.dateRange2);

    legendItems.value = [
      { label: '地表破裂带', color: 'rgba(234,64,53,1)', w: 10, h: 2, r: 0 },
      { label: '震中', color: 'rgba(234,64,53,1)', w: 10, h: 10, r: 50 },
    ];
  } else {
  }
};

// 跳转各省局
const goToSecond = () => {
  router.push({ path: '/geologicalDisaster/second', query: { provinceName: '四川省' } });
};
</script>

<style scoped lang="scss">
.app-container {
  min-height: 1080px;
}
.app-main {
  display: flex;
  justify-content: space-between;
  .app-left {
    margin-left: 30px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    width: 450px;
    &-item {
      width: 450px;
      // background: linear-gradient(135deg, #00032D 0%, #000C58 50%, #00032D 100%);
      // opacity: .85;
      background: linear-gradient(
        135deg,
        rgba(0, 3, 45, 0.85) 0%,
        rgba(0, 12, 88, 0.85) 50%,
        rgba(0, 3, 45, 0.85) 100%
      );
      position: relative;
      &::after {
        content: '';
        display: block;
        width: 450px;
        height: 20px;
        background-size: 100% 100%;
        background-image: url('../../assets/images/common/bg_bottom.png') !important;
      }
      &:nth-child(1) {
        height: 280px;
      }
      &:nth-child(2) {
        height: 280px;
      }
      &:nth-child(3) {
        height: 300px;
      }
    }
  }

  .app-map {
    width: 960px;
    height: 100%;
    overflow: visible;
  }
  .app-right {
    margin-right: 30px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    width: 450px;

    &-item {
      width: 450px;
      background: linear-gradient(
        135deg,
        rgba(0, 3, 45, 0.85) 0%,
        rgba(0, 12, 88, 0.85) 50%,
        rgba(0, 3, 45, 0.85) 100%
      );
      position: relative;
      &::after {
        content: '';
        display: block;
        width: 450px;
        height: 20px;
        background-size: 100% 100%;
        background-image: url('../../assets/images/common/bg_bottom.png') !important;
        /*position: static;*/
      }
      &:nth-child(1) {
        height: 180px;
      }
      &:nth-child(2) {
        height: 500px;
        z-index: 9;
      }
      &:nth-child(3) {
        z-index: 9;
        &::after {
          content: '';
          display: block;
          width: 450px;
          height: 20px;
          background-size: 100% 100%;
          background-image: url('../../assets/images/common/bg_bottom.png') !important;
          position: static;
        }
      }
    }
  }
}
</style>
